import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { stripesConnect,IfPermission } from '@folio/stripes/core';
import { FormattedMessage, injectIntl } from 'react-intl';
import { get } from 'lodash';
import {
  StripesConnectedSource,

} from '@folio/stripes/smart-components';
import {
  Button,
  MultiColumnList,
  ButtonGroup
} from '@folio/stripes/components';
import SearchForm from '../../components/party-auxiliary/search-form';

class List extends Component {
  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    history:PropTypes.object,
    mutator: PropTypes.shape({

      auxiliaryQuery: PropTypes.string,
      equipmentRecords: PropTypes.shape({
        PUT: PropTypes.func.isRequired,
        POST: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired,
        DELETE: PropTypes.func.isRequired
      })
    }).isRequired,
    toModel: PropTypes.func
  };

  // eslint-disable-next-line react/sort-comp
  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      searchForm: {},
      editOpen: false,
      editParams: {}
    };
  }

  static manifest = Object.freeze({

    auxiliaryQuery: { initialValue: '' },
    resultCount: { initialValue: 10 },
    equipmentRecords: {
      type: 'okapi',
      records: 'auxiliaryGroup',
      limitParam: 'limit',
      path: 'party/auxiliary',
      recordsRequired: '%{resultCount}',
      perRequest: 30,
      GET: {
        params: {
          query: '( isDel = 0  ${auxiliaryQuery} ) sortby metadata.updateDate'
        }
      }
    }
  });

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
  }

  componentDidUpdate() {
    this.source.update(this.props, 'equipmentRecords');
  }

  search = ({ ...formData }) => {
    const { mutator } = this.props;

    let query = Object.getOwnPropertyNames(formData)
      .map(key => {
        return Number(formData[key])
          ? `${key} = ${formData[key]}`
          : `${key} = "${formData[key]}*" `;
      })
      .join(' and ');
    if (query) {
      query = 'and ' + query;
    }
    mutator.auxiliaryQuery.replace(query);

    if (this.source) {
      this.source.update(this.props, 'equipmentRecords');
    }
  };

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(10);
    }
  };

  add=() => {
    const { resources, toModel } = this.props;
    toModel('/party/auxiliary/add');
  }

  delData = formData => {
    const { mutator ,intl} = this.props;

    if (confirm(intl.formatMessage({id:"ui-party.other.are.you.sure.to.delete.this.resource"}))) {

      mutator.equipmentRecords.DELETE({ id: formData.id }).then(() => {

      });
    }
  };

  render() {
    const { resources, toModel } = this.props;
    if (this.source) {
      this.source.update(this.props, 'equipmentRecords');
    }

    const able = document.getElementsByClassName('mclScrollable---IM56u');
    if (able && able[0]) {
      able[0].style.width = '105%';
    }

    const totalCount = this.source ? this.source.totalCount() : 0;
    const dataList = get(resources, 'equipmentRecords.records', []);

    const formatter = {
      serialNumber: (
        <FormattedMessage id="ui-party.loans.columns.serialNumber" />
      ),
      typeName: <FormattedMessage id="ui-party.loans.columns.source.type" />,
      name: <FormattedMessage id="ui-party.loans.columns.source.name" />,
      remainder: <FormattedMessage id="ui-party.loans.columns.source.remainder" />,
      amount: <FormattedMessage id="ui-party.loans.columns.source.amount" />,
      state: <FormattedMessage id="ui-party.loans.columns.source.state" />,
      author: <FormattedMessage id="ui-party.loans.columns.source.author" />,
      edit: <FormattedMessage id="ui-party.loans.columns.operating.edit" />
    };
    return (
      <div style={{ width:'100%', height:'580px' }}>
        <SearchForm onSubmit={this.search} add={this.add} toModel={toModel} />
        <MultiColumnList
          autosize
          virtualize
          interactive={false}

          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          totalCount={totalCount}
          contentData={dataList}
          onNeedMoreData={this.moreData}
          columnMapping={formatter}
          columnWidths={{
            serialNumber: '10%',
            typeName: '10%',
            name: '20%',
            amount: '10%',
            remainder: '10%',
            state: '10%',
            edit: '20%',
            author: '10%'
          }}
          visibleColumns={[
            'serialNumber',
            'typeName',
            'name',
            'amount',
            'remainder',
            'state',
            'author',
            'edit'
          ]}
          formatter={{
            typeName: item => {
              if (item.typeName === 1) {
                return  <FormattedMessage id={"ui-party.loans.columns.source.venue"}/>;
              } else if (item.typeName === 2) {
                return <FormattedMessage id={"ui-party.loans.columns.source.device"}/>;
              }
            },
            state: item => {
              if (item.state === 0) {
                return  <FormattedMessage id={"ui-party.loans.columns.party.noneffective"}/>;
              } else if (item.state === 1) {
                return  <FormattedMessage id={"ui-party.loans.columns.party.effective"}/>;
              }
            },
            serialNumber: item => [<span>{item.rowIndex + 1}</span>],
            edit: item => [
              <ButtonGroup>
                <IfPermission perm={"ui-party.auxiliary.manage.view.edit"}>
                  <Button
                      onClick={() => {
                        toModel('/party/auxiliary/edit', { id:item.id });
                      }}
                  >
                    <FormattedMessage id={"ui-party.loans.columns.operating.edit"}/>
                  </Button>
                </IfPermission>
                <IfPermission perm={"ui-party.auxiliary.manage.view.delete"}>
                <Button
                  style={{ border: '1px solid #900', color: ' #900' }}

                  onClick={() => {
                    this.delData(item);
                  }}
                >
                   <FormattedMessage id={"ui-party.loans.columns.operating.remove"}/>
                </Button>
                </IfPermission>
              </ButtonGroup>
            ]
          }}
        />
      </div>
    );
  }
}

List.propTypes = {};

export default injectIntl(stripesConnect(List));
